package com.axjc.gqzr.util;

import com.axjc.gqzr.common.CommonKey;
import com.axjc.gqzr.config.JwtService;
import com.axjc.gqzr.domain.SysUser;
import com.axjc.gqzr.mapper.SysUserMapper;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 实现ApplicationContextAware接口设置applicationContext
 * 提供static方法供调用者使用，不要求使用者受spring容器管理
 */
@Component
public class ApplicationContextUtil implements ApplicationContextAware {

    public static ApplicationContext applicationContext;

    //    SysUserMapper userMapper;
    JwtService jwtService;

    public static SysUser GetCurrentUser() {

        String token = getToken();
        if (token == null) {
            throw new NullPointerException("token is null");
        }
        SysUserMapper userMapper = ApplicationContextUtil.getBean(SysUserMapper.class);
        JwtService jwtService = ApplicationContextUtil.getBean(JwtService.class);
        String username = jwtService.extractUsername(token);
        return userMapper.findByUserName(username);

    }

    private static String getToken() {
        String token = ApplicationContextUtil.GetParameter(CommonKey.Token);
        if (token == null) {
            String authorization = getRequest().getHeader("Authorization");
            token = authorization.substring(7);
        }
        return token;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ApplicationContextUtil.applicationContext = applicationContext;
    }


    public static HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
    }

    public static String GetParameter(String key) {
        return getRequest().getParameter(key);
    }

    public static ApplicationContext getApplicationContext() {
        return ApplicationContextUtil.applicationContext;
    }

    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }

    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }

    public static <T> T getBean(String name, Class<T> clazz) {
        return getApplicationContext().getBean(name, clazz);
    }
}

